package com.itheima.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class DataSourceUtil {

    private static final  ThreadLocal<Connection> CONNECTION_THREAD_LOCAL=new ThreadLocal<>();




    public static Connection getConnection(DataSource dataSource) throws SQLException {

        //先看看有木有放进去?
        Connection connection = CONNECTION_THREAD_LOCAL.get();
        if (connection==null){
            //没有咋办?
            connection= dataSource.getConnection();
            //放入当前线程中去
            CONNECTION_THREAD_LOCAL.set(connection);
        }
        return connection;
    }

    public static void close(){
        //关闭资源
        try {
            Connection connection =CONNECTION_THREAD_LOCAL.get();
            if (connection!=null){
                //先从当前线程中 移除
                CONNECTION_THREAD_LOCAL.remove();

                connection.close();
            }


        }catch (Exception e){
            //do noting~~~
        }



    }









}
